/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.dailyexpress.mongodbdao;

import com.elcom.dailyexpress.mongodbobject.MessageIdSequence;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.WriteConcern;
import org.bson.types.ObjectId;

/**
 *
 * @author GiangLT
 */
public class MessageIdDao extends BasicDAO<MessageIdSequence, ObjectId> {

    private static MessageIdDao instance;

    private MessageIdDao(Datastore ds) {
        super(ds);
    }

    public static synchronized MessageIdDao getInstance(Datastore ds) {
        if (instance == null) {
            instance = new MessageIdDao(ds);
        }
        return instance;
    }

    public synchronized int getSequence() {
        QueryResults<MessageIdSequence> results = instance.find();
        if (results == null || results.countAll() == 0) {
            MessageIdSequence messageIdSequence = new MessageIdSequence(1);
            instance.save(messageIdSequence, WriteConcern.ACKNOWLEDGED);
            return 0;
        } else {
            MessageIdSequence messageIdSequence = results.asList().get(0);
            Integer seq = messageIdSequence.getSequence();
            ObjectId objectId = messageIdSequence.getMongoId();

            Query<MessageIdSequence> updateQuery = ds.createQuery(MessageIdSequence.class).field(Mapper.ID_KEY).equal(objectId);
            UpdateOperations<MessageIdSequence> updateOperations = ds.createUpdateOperations(MessageIdSequence.class).inc("sequence");
            ds.update(updateQuery, updateOperations);
            return seq;

        }
    }
}
